<?php
require("HTMLFunctions.php");
require("ValidationFunctions.php");

//database
require('ac_db.inc.php');

//set error reporting
error_reporting(E_ERROR | E_WARNING);

//set credentials for database
setcredentials("tr2286","databases8620", "w4111b.cs.columbia.edu/ADB");

//create DB instance
$db = new Db("Proj1", "Part3");


//declare vars of this script
$errorText = "";
$errorArray = array();
$correctEntries = array();

//ensure that input is not blank which would mean that the site is illegally accessed
if(count($_POST) == 0){
	
	//if so, redirect to login
	$db->closeSession();
	echo "<meta http-equiv='refresh' content='0;url=http://localhost/login.php'>";
	exit;
}

//if the only input is username i.e. the size is 1
//then no update was performed yet
if(count($_POST) == 1){
	
	//this method will return an array with all the information
	$correctEntries = $db -> getCustomerDetails($_POST['email']);
	$correctEntries['firstName'] = $correctEntries['FIRST_NAME'];
	$correctEntries['lastName'] = $correctEntries['LAST_NAME'];
	$correctEntries['city'] = $correctEntries['CITY'];
	$correctEntries['state'] = $correctEntries['STATE'];
	$correctEntries['country'] = $correctEntries['COUNTRY'];
	$correctEntries['zip'] = $correctEntries['ZIP'];
	$correctEntries['address'] = $correctEntries['ADDRESS'];
	$correctEntries['phoneNumber'] = $correctEntries['PHONE_NUMBER'];
	$correctEntries['email'] = $_POST['email'];
	
	#now call the subroutine to display the update form
	displayUpdate($errorText, $errorArray, $correctEntries, $db);
}

//otherwise we know that further information was submitted to the script so we verify if the user made valid changes
else{
	
	//now call function to process input
	//this function will take control of the flow of the script and determine what actions to further take
	processUpdate($errorText, $errorArray, $correctEntries, $db);
}

//function to both determine the validity of the users input and to process all data
//this function will call a subroutine to determine if each of the data fields was entered correctly
//each of those decisions will be stored in a "boolean" variable so the script can then notify the user of all errors individually
function processUpdate($errorText, $errorArray, $correctEntries, $db){
	
	//call functions to validate update
	$validFName = ValidationFunctions::validateName($_POST['firstName']);
	$validLName = ValidationFunctions::validateName($_POST['lastName']); 
	$validAddress =  ValidationFunctions::validateName($_POST['address']);
	$validCity =  ValidationFunctions::validateName($_POST['city']);
	$validCountry =  ValidationFunctions::validateName($_POST['country']);
	$validState =  ValidationFunctions::validateName($_POST['state']);
	$validZip =  ValidationFunctions::validateName($_POST['zip']);
	$validPhone =  ValidationFunctions::validatePhone($_POST['phoneNumber']);
	
	//ensure that enverything was submitted correctly
	if($validFName == true && $validLName == true && $validAddress == true && $validCity == true && $validCountry == true && $validState == true && $validZip == true && $validPhone == true ) {
		
		$db -> updateUser($_POST);
		$db -> commit();
		
		//lastly call function to show success
		showSuccess($_POST['email'], $db);
	}
	#otherwise show submission screen again with proper error messages
	else{
		
		//now go through each submission and add error messages or correct values
		//first name
		if($validFName == true){
			
			//add value to correct and blank to error
			$correctEntries['firstName'] = $_POST['firstName'];
			$errorArray['firstName'] = "";
		}
		else{
			
			//add blank to correct and message to error
			$correctEntries['firstName'] = "";
			$errorArray['firstName'] = "<tr><td></td><td><font color=\"red\" size=\"2\">Invalid First Name Given</font></td></tr>";
		}
		
		//last name
		if($validLName == true){
			
			//add value to correct and blank to error
			$correctEntries['lastName'] = $_POST['lastName'];
			$errorArray['lastName'] = "";
		}
		else{
			
			//add blank to correct and message to error
			$correctEntries['lastName'] = "";
			$errorArray['lastName'] = "<tr><td></td><td><font color=\"red\" size=\"2\">Invalid Last Name Given</font></td></tr>";
		}
		
		//address
		if($validAddress == true){
			
			//add value to correct and blank to error
			$correctEntries['address'] = $_POST['address'];
			$errorArray['address'] = "";
		}
		else{
			
			//add blank to correct and message to error
			$correctEntries['address'] = "";
			$errorArray['address'] = "<tr><td></td><td><font color=\"red\" size=\"2\">Invalid Address Given</font></td></tr>";
		}
		
		//city
		if($validCity == true){
			
			//add value to correct and blank to error
			$correctEntries['city'] = $_POST['city'];
			$errorArray['city'] = "";
		}
		else{
			
			//add blank to correct and message to error
			$correctEntries['city'] = "";
			$errorArray['city'] = "<tr><td></td><td><font color=\"red\" size=\"2\">Invalid City Given</font></td></tr>";
		}
		
		//country
		if($validCountry == true){
			
			//add value to correct and blank to error
			$correctEntries['country'] = $_POST['country'];
			$errorArray['country'] = "";
		}
		else{
			
			//add blank to correct and message to error
			$correctEntries['country'] = "";
			$errorArray['country'] = "<tr><td></td><td><font color=\"red\" size=\"2\">Invalid Country Given</font></td></tr>";
		}
		
		//state
		if($validState == true){
			
			//add value to correct and blank to error
			$correctEntries['state'] = $_POST['state'];
			$errorArray['state'] = "";
		}
		else{
			
			//add blank to correct and message to error
			$correctEntries['state'] = "";
			$errorArray['state'] = "<tr><td></td><td><font color=\"red\" size=\"2\">Invalid State Given</font></td></tr>";
		}
		
		//zip
		if($validZip == true){
			
			//add value to correct and blank to error
			$correctEntries['zip'] = $_POST['zip'];
			$errorArray['zip'] = "";
		}
		else{
			
			//add blank to correct and message to error
			$correctEntries['zip'] = "";
			$errorArray['zip'] = "<tr><td></td><td><font color=\"red\" size=\"2\">Invalid Zip Given</font></td></tr>";
		}
		
		//phoneNumber
		if($validPhone == true){
			
			//add value to correct and blank to error
			$correctEntries['phoneNumber'] = $_POST['phoneNumber'];
			$errorArray['phoneNumber'] = "";
		}
		else{
			
			//add blank to correct and message to error
			$correctEntries['phoneNumber'] = "";
			$errorArray['phoneNumber'] = "<tr><td></td><td><font color=\"red\" size=\"2\">Invalid Phone Number Given</font></td></tr>";
		}
		
		//set email correctly
		$correctEntries['email'] = $_POST['email'];
		
		//now that the individual errors were determined, call the subroutine to re-display the form and pass it the proper values and error messages
		//declare error message
		$errorText = "<h4><font color=\"red\">Some information was incorrectly entered. <br>Please see the individual fields for details and try again.</font></h4>";
		displayUpdate($errorText, $errorArray, $correctEntries, $db);
	}
}

//function that is called whenever the user succesfully submits his/her data
//this function will display a success message to the user before redirecting to the main window
//the function is passed two parameters, the users first name and the username
function showSuccess($email, $db){
	
	//call method to display html beginnign
	HTMLFunctions::printHTMLHead("Successfully Updated Account!");
	
	HTMLFunctions::generateTitleBar("Account Updated Successfully",$email, $db);
	
	echo <<<END_HTML
	
	<!--now display the message to the user-->
	<h4>Please proceed to your profile for further action.</h4>
	<br>
	
END_HTML;

	//create array for button
	$parameterArray = array();
	$parameterArray['email'] = $email;
	
	//call subroutine to display button that returns the user to the profile
	HTMLFunctions::generateButton("profile.php", "Go To profile", $parameterArray);
	
	//close db connection
	$db->closeSession();

	//now call method to produce closing html tags
	HTMLFunctions::printHTMLEnd();
}

//subroutine to display the update page
//this subroutine takes three potential parameters, one which is an error message or any text to be displayed above the form
//and the other is an array of error messages associated with individual fields
//and the last one is a hash of previously entered correct values
function displayUpdate($errorText, $errorArray, $correctEntries, $db){
	
	//call functions to create the html headers
	HTMLFunctions::printHTMLHead("Online Portfolio Management");
	
	//call the function to create the html code for the actual form
	generateUpdateHTML($errorText, $errorArray, $correctEntries, $db);
	
	//close db connection
	$db->closeSession();
	
	//call the function to end the html code
	HTMLFunctions::printHTMLEnd();
}

//function to create the html update form
function generateUpdateHTML($errorText, $errorArray, $correctEntries, $db){
	
	//create a parameter array to pass to the function to display the generic header
	$parameterArray = array();
	$parameterArray['email'] = $_POST['email'];
	
	#call sub to print header
	HTMLFunctions::generateTitleBar("Update User", $_POST['email'], $db);
	
	//print potential error message
	echo($errorText);
	
	echo <<<END_HTML
	<!--content-->
	<!-- place form in table for appearance formatting-->
	<!-- individual error messages are displayed below the designated fields if those messages are not intentionally left blank-->
		<table>
			<form action="updateUser.php" method=POST>
			<tr>
				<!-- first name-->
				<td><p>First Name:*</p></td>
				<td><input type="text" name="firstName" value="{$correctEntries['firstName']}"></td>
			</tr>
			{$errorArray['firstName']}
			<tr>
				<!-- last name-->
				<td><p>Last Name:*</p></td>
				<td><input type="text" name="lastName" value="{$correctEntries['lastName']}"></td>
			</tr>
			{$errorArray['lastName']}
			<tr>
				<!-- email-->
				<td><p>Email:*</p></td>
				<td><input type="text" name="email" value="{$correctEntries['email']}" readonly></td>
			</tr>
			<tr>
				<!-- Address-->
				<td><p>Address:*</p></td>
				<td><input type="text" name="address" value="{$correctEntries['address']}"></td>
			</tr>
			{$errorArray['address']}
			<tr>
				<!-- City-->
				<td><p>City:*</p></td>
				<td><input type="text" name="city" value="{$correctEntries['city']}"></td>
			</tr>
			{$errorArray['city']}
			<tr>
				<!-- State-->
				<td><p>State:*</p></td>
				<td><input type="text" name="state" value="{$correctEntries['state']}"></td>
			</tr>
			{$errorArray['state']}
			<tr>
				<!-- Country-->
				<td><p>Country:*</p></td>
				<td><input type="text" name="country" value="{$correctEntries['country']}"></td>
			</tr>
			{$errorArray['country']}
			<tr>
				<!-- Zip-->
				<td><p>Zip:*</p></td>
				<td><input type="text" name="zip" value="{$correctEntries['zip']}"></td>
			</tr>
			{$errorArray['zip']}
			<tr>
				<!-- Phone-->
				<td><p>Phone Number:*</p></td>
				<td><input type="text" name="phoneNumber" value="{$correctEntries['phoneNumber']}"></td>
			</tr>
			{$errorArray['phoneNumber']}
			<tr>
				<!-- submit button and cancel button-->
				<td><input type="submit" value="Submit"></form></td>
			</tr>
			<tr>
				<td>
END_HTML;
		//call function to crate a cancel button
		//this button will link back to login
		HTMLFunctions::generateButton("profile.php", "Cancel", $parameterArray);
		
		//print remaining tags
		echo <<<END_HTML
			</td>
			</tr>
			<tr>
			<td>
			
END_HTML;
		//call function to create a button to link to change password
		HTMLFunctions::generateButton("changePassword.php", "ChangePassword", $parameterArray);
				
		#print remainder of html tags
		echo <<<END_HTML
		</td>
		</tr>
		</table>
END_HTML;


}